#include "httpSession.h"
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <chrono>
#include <iomanip>
#include <thread>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#define MAX_BUFFER_128KSZ				0x20000
#define MAX_BUFFER_4KSZ					0x1000	 //4k
#define BUFLEN 4 * 4096

#ifndef WIN32
#include <iconv.h> 
#endif

#include "log4z.h"
#include "common.h"
#include "osip_net.h"
#include "internal.h"

//API
#include "deviceModel.h"

std::mutex MutexMapSession;
std::mutex MutexMapFile;
static std::map<std::string, std::string> mMapFile;

CHTTPSession::CHTTPSession()
{
	m_fdClient = SOCKET_ERROR;
	//m_RecvBye = TimGetTicks();
	m_HttpBuffer = new CHttpBuffer(2048);
	initApiMap1();
	initApiMap2();
	initApiMap4();
	initApiMapGet();
	LOGFMTI("%s", __func__);
}

CHTTPSession::~CHTTPSession()
{
	StopServer();
	SAFE_DELETE(m_HttpBuffer);
	LOGFMTI("%s", __func__);

	for (auto& m : m_funModel)
	{
		if (m.second != nullptr)
			delete m.second;
	}

	m_funModel.clear();
}

void CHTTPSession::initApiMap1() {
	//msg1
	//apiMap1["/user/login"] = { &CHTTPSession::UserLogin, "POST", "", "" };
}

void CHTTPSession::initApiMap2() {
#if defined SPJZZMWG_WEBSERVER
	apiMap2["/dashboard/onlineTime"] = { &CHTTPSession::onlineTime, "POST", "", "" };
	apiMap2["/dashboard/subSer"] = { &CHTTPSession::subSer, "POST", "", "" };
	apiMap2["/dashboard/serviceChannel"] = { &CHTTPSession::serviceChannel, "POST", "", "" };
	// apiMap2["/logConf/findLogConf"] = { &CHTTPSession::findLogConf, "POST", "", "" };
#endif
}

void CHTTPSession::initApiMap4() {
	//apiMap4["/sqlite3/execSQLFunc"] = { &CHTTPSession::execSQLFunc, "POST", "", "" };
	//apiMap4["/sqlite3/rawQueryFunc"] = { &CHTTPSession::rawQueryFunc, "POST", "", "" };
}

void CHTTPSession::initApiMapGet() {
	// apiMapGet["/api/v1/device/list"] = { &CHTTPSession::device_list, "GET", "", "" };
	// apiMapGet["/api/v1/device/channellist"] = { &CHTTPSession::device_channellist, "POST", "", "" };
	m_funModel["device"] = new deviceModel();
}

void CHTTPSession::setClientIp(const char* str)
{
	m_strClientIp = str;
}

int CHTTPSession::StopServer()
{
	fdClose(m_fdClient);
	return XX_ERR_ERROR;
}

int CHTTPSession::StartServer(const socket_t fdClient)
{
	m_fdClient = fdClient;

	if (mMapFile.empty()) {
		char szPath[256] = { 0 };
		char* path = GetExeFilePaths(szPath, "www");
		std::string directory = path;
		GetFilePaths(path, mMapFile);

		for (const auto& pair : mMapFile) {
			std::cout << pair.first << ": " << pair.second << std::endl;
		}
	}

	return 0;
}

int CHTTPSession::sendMessage(const char* data, int len)
{
	// LOGFMTE("----  %s",data);
	LOGFMTI("---- send data len: %d", len);
	if (!data || len <= 0) {
		return -1;
	}
	if (-1 == m_fdClient) {
		return 0;
	}

	int dwRepeate = 0;
	int dwByte, dwWrite = 0;

	do {
#ifdef WIN32
		dwByte = send(m_fdClient, data + dwWrite, len, 0);
		if (dwByte < 0) {
			if ((WSAEWOULDBLOCK == WSAGetLastError()) && (dwRepeate++ < 3)) {
				Sleep(20);
				continue;
			}
			return XX_ERR_NONE;
		}
#else
		dwByte = send(m_fdClient, data + dwWrite, len, MSG_NOSIGNAL);
		if (dwByte <= 0) {
			// if ((EAGAIN == errno) && (dwRepeate++ < 30)) {
			if ((EAGAIN == errno)) {
				LOGFMTE("Error1(%d): %s", errno, strerror(errno));
				usleep(10000);
				continue;
	}
			LOGFMTI("----------------------");
			LOGFMTE("Error2(%d): %s", errno, strerror(errno));
			return XX_ERR_NONE;
}
#endif
		len -= dwByte;
		dwWrite += dwByte;
	} while (len > 0);
	LOGFMTI("=======================");
	return dwWrite;
}

void CHTTPSession::sendBodyMessage(const char* data, int len)
{
	LOGFMTI("send data len:%d", len);
	sendMessage(data, len);
}

void CHTTPSession::sendJsonMessage(const char* data, int len)
{
	if (!m_HttpBuffer) {
		LOGFMTE("m_HttpBuffer null");
		return;
	}
	int httplen = CHttpResponse::make(m_HttpBuffer->m_chars, len, "application/json;charset=UTF-8");
	m_HttpBuffer->m_chars[httplen] = 0;
	if (sendMessage(m_HttpBuffer->m_chars, httplen) > 0) {
		sendBodyMessage(data, len);
	}
}

void CHTTPSession::sendTextMessage(const char* data, int len)
{
	if (!m_HttpBuffer) {
		LOGFMTE("m_HttpBuffer null");
		return;
	}
	int httplen = CHttpResponse::make(m_HttpBuffer->m_chars, len, "text/plain;charset=UTF-8");
	m_HttpBuffer->m_chars[httplen] = 0;
	if (sendMessage(m_HttpBuffer->m_chars, httplen) > 0) {
		sendBodyMessage(data, len);
	}
}

void CHTTPSession::send200Message()
{
	cJSON* JsonObject1 = cJSON_CreateObject();
	cJSON_AddItemToObject(JsonObject1, "code", cJSON_CreateNumber(200));
	cJSON_AddItemToObject(JsonObject1, "msg", cJSON_CreateString("成功"));
	cJSON_AddItemToObject(JsonObject1, "data", cJSON_CreateString(""));

	sendJson(JsonObject1);
}

void CHTTPSession::send400Message(const char* data, int len)
{
	char* buffer = new char[1024];
	if (buffer) {
		char* ptr = buffer;
		ptr += sprintf(ptr, "HTTP/1.1 400 Bad Request\r\n");
		ptr += sprintf(ptr, "User-Agent: xxxx\r\n");
		ptr += sprintf(ptr, "Content-Type: text/plain; charset=UTF-8\r\n");
		ptr += sprintf(ptr, "Connection: keep-alive\r\n");
		ptr += sprintf(ptr, "Content-Length: %d\r\n", len);
		ptr += sprintf(ptr, "\r\n");
		sendMessage(buffer, int(ptr - buffer));
		sendMessage(data, len);
		delete[] buffer;
	}
	else {
		LOGFMTE("buffer null");
	}
}

void CHTTPSession::send404Message(const char* data, int len)
{
	char* buffer = new char[1024];
	if (buffer) {
		char* ptr = buffer;
		ptr += sprintf(ptr, "HTTP/1.1 404 Not Found\r\n");
		ptr += sprintf(ptr, "User-Agent: xxxx\r\n");
		ptr += sprintf(ptr, "Content-Type: text/plain; charset=UTF-8\r\n");
		ptr += sprintf(ptr, "Connection: keep-alive\r\n");
		ptr += sprintf(ptr, "Content-Length: %d\r\n", len);
		ptr += sprintf(ptr, "\r\n");

		sendMessage(buffer, int(ptr - buffer));
		sendMessage(data, len);
		delete[] buffer;
	}
	else {
		LOGFMTE("buffer null");
	}
}

void CHTTPSession::send401Message(const char* data, int len)
{
	std::string inStr = "用户名密码错误请重新输入";
#if 0
	int nLength;
#if WIN32
	char* strUtf = G2U(inStr.c_str(), nLength);
#else
	char* outbuf = new char[BUFLEN];
	if (!outbuf) {
		LOGFMTE("outbuf null");
		return;
	}
	GB2312ToUTF_8(&nLength, outbuf, (char*)inStr.c_str(), inStr.length(), BUFLEN);
	LOGFMTI("nLength: %d    %s", nLength, outbuf);
#endif
#endif
	char* buffer = new char[1024];
	if (!buffer) {
		//delete[] outbuf;
		LOGFMTE("buffer null");
		return;
	}
	char* ptr = buffer;
	ptr += sprintf(ptr, "HTTP/1.1 401 Unauthorized\r\n");
	ptr += sprintf(ptr, "User-Agent: xxxx\r\n");
	ptr += sprintf(ptr, "Content-Type: text/plain; charset=UTF-8\r\n");
	ptr += sprintf(ptr, "Connection: keep-alive\r\n");
	ptr += sprintf(ptr, "Content-Length: %d\r\n", len);
	ptr += sprintf(ptr, "\r\n");
	sendMessage(buffer, int(ptr - buffer));
	sendMessage(data, len);
	delete[] buffer;
	//delete[] outbuf;
}

void CHTTPSession::send302Message(const char* data)
{
	CData moveTo(data);
	CData strLocation(data);
	CData strContent;
	strContent += "<a href=\"";
	strContent += moveTo;
	strContent += "\">Found</a>";

	CData strResp;
	char szTemp[256] = { 0 };
	sprintf(szTemp, "Content-Length: %d\r\n", (int)strContent.size());

	strResp = "HTTP/1.1 302 Found\r\n";
	strResp += "Server: http_util\r\n";
	strResp += "Content-Type: text/html; charset=UTF-8\r\n";
	strResp += szTemp;
	strResp += "Connection: keep-alive\r\n";
	strResp += "Location: ";
	strResp += strLocation + "\r\n";
	strResp += "\r\n";

	sendMessage(strResp.c_str(), strResp.size());
	sendMessage(strContent.c_str(), strContent.size());
}

int CHTTPSession::run()
{
	// 获取当前时间点
	auto start_time = std::chrono::steady_clock::now();

	int nRecvByte = 0;
	fd_set fdRead = { 0 };
	struct timeval  tv = { 0 };
	//char buffer[MAX_BUFFER_4KSZ];
	rx_buf.clear();
	char* buffer = (char*)malloc(MAX_BUFFER_4KSZ);
	if (!buffer) {
		LOGFMTE("buffer null");
		return 0;
	}

#ifndef WIN32
	prctl(PR_SET_NAME, "CHTTPSession");
#endif

	while (1) {
		// 在循环内部检查循环时间
		auto current_time = std::chrono::steady_clock::now();
		auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(current_time - start_time).count();

		if (elapsed_time >= 60) {
			// 如果循环时间超过60秒，退出循环
			LOGFMTE("If the cycle time exceeds 60 seconds, exit the cycle");
			break;
		}

		tv.tv_sec = 0;
		FD_ZERO(&fdRead);
		tv.tv_usec = 500 * 1000;
		FD_SET(m_fdClient, &fdRead);
#ifdef _WIN32
		if (select(m_fdClient, &fdRead, NULL, NULL, &tv) > 0) {
#else
		if (select(m_fdClient + 1, &fdRead, NULL, NULL, &tv) > 0) {
#endif
			if (FD_ISSET(m_fdClient, &fdRead))
			{
				{
					long int numBytes;
					std::size_t nHttpHead = 0;
					bool isheaders = false;
					bool type = false;
					while ((numBytes = recv(m_fdClient, buffer, MAX_BUFFER_4KSZ - 1, 0)) > 0) {
						// buffer[numBytes] = '\0';
						// receivedContent += buffer;
						rx_buf.append(buffer, numBytes);

						// 判断是否已经接收到完整的 HTTP 头部
						nHttpHead = rx_buf.getBuf().find("\r\n\r\n") + strlen("\r\n\r\n");
						if (nHttpHead != std::string::npos) {
							// 在这里对接收到的完整 HTTP 头部进行处理
							isheaders = true;
							LOGFMTI("Received complete HTTPT header : %ld", nHttpHead);
							// std::cout << "Received HTTP headers: " << rx_buf.getBuf() << std::endl;
						}
						else {
							if (numBytes == 0) {
								LOGFMTI("没有收到完整 HTTPT 头,接收到0字节,接收结束 : %ld", rx_buf.size());
								break;
							}
							LOGFMTI("没有收到完整 HTTPT 头,继续接收 : %ld", rx_buf.size());
							continue;
						}

						// 判断是否已经接收到完整的 HTTP 内容
						std::size_t contentLengthPos = rx_buf.getBuf().find("Content-Length:");
						if (contentLengthPos != std::string::npos) {
							std::size_t endOfLinePos = rx_buf.getBuf().find("\r\n", contentLengthPos);
							if (endOfLinePos != std::string::npos) {
								std::string contentLengthValue = rx_buf.getBuf().substr(contentLengthPos + 15, endOfLinePos - contentLengthPos - 15);
								int contentLength = std::stoi(contentLengthValue);

								if (rx_buf.getBuf().length() - nHttpHead >= (size_t)contentLength) {
									type = true;
									LOGFMTI("已经接收到完整的 HTTP 内容 : %ld", rx_buf.getBuf().length());
									break;
								}
							}
						}
						else if (isheaders) {
							type = true;
						}
					}

					if (numBytes == 0) {
						// 对端已关闭连接
						LIMIT_LOG_RATE(30) {
							LOGFMTE("Connection closed by the remote host close fd:%d, %s", m_fdClient, get_ip_prot(m_fdClient).c_str());
						}
						break;
					}
#ifdef _WIN32
					else if (numBytes == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK) {
						LOGFMTE("close fd:%d, %s", m_fdClient, get_ip_prot(m_fdClient).c_str());
						LOGFMTE("Connection failed%s", WSAGetLastError());
						break;
					}
#else
					else if (numBytes == -1) {
						// 接收过程中发生错误
						LIMIT_LOG_RATE(30) {
							LOGFMTE("Error in recv: (%d) %s", errno, strerror(errno));
						}
						if (errno == EAGAIN || errno == EWOULDBLOCK) {
							// 暂时没有数据可用，可以选择等待或进行其他操作
						}
						else if (errno == EINTR) {
							// 接收过程被信号中断，可以选择重新调用 recv() 或进行其他操作
					}
						else {
							// 其他错误情况，进行相应的错误处理
							LOGFMTI("close fd:%d, %s", m_fdClient, get_ip_prot(m_fdClient).c_str());
							break;
						}
				}
#endif
					if (type) {
						if (rx_buf.getBuf().size() >= 0) {
							OnReceive(rx_buf.getBuf().c_str(), rx_buf.getBuf().size());
							// printf("%s\n", rx_buf.getBuf().c_str());
							rx_buf.clear();
							LOGFMTI("||||||||||||||    http  work  data_len:%d  cfd:%d end  ||||||||||||||\n", rx_buf.getBuf().size(), m_fdClient);
						}
						else {
							LOGFMTE("rx_buf.getBuf().size():%d", rx_buf.getBuf().size());
						}
						//先在超融合测试，不影响盒子
#if defined AQRH_WEBSERVER
						break;
#else
						break;
#endif
					}
					else {
						LIMIT_LOG_RATE(30) {
							LOGFMTE("Incomplete received data");
							continue;
						}
					}
			}
		}
		}
		}
	SAFE_FREE(buffer);
	fdClose(m_fdClient);
	LOGFMTI("end");
	return 0;
	}

int CHTTPSession::CheckActive()
{
	if ((TimGetTicks() - m_RecvBye) < 60 * 1000) {
		return XX_ERR_NONE;
	}
	return XX_ERR_ERROR;
}

bool CHTTPSession::CheckToken(std::string & Authorization) {
	bool istmp = true;
#if TOKEN
	bool bIsExist = false;
	std::lock_guard<std::mutex> lock(MutexMapSession);
	for (auto it = mMapSession.begin(); it != mMapSession.end();)
	{
		loginUserInfo* ploginUserInfo = it->second;
		unsigned int dwCurTime = TimGetTicks();
		unsigned int cur_time = ploginUserInfo->last_time;
		unsigned int temp_time_out = ConfigInfo::instance()->page_timeout.ToInt() * 60 * 1000;
		if (0 != temp_time_out && dwCurTime - cur_time > temp_time_out) {
			if (it->first == Authorization) {
				cJSON* JsonObject1 = cJSON_CreateObject();
				cJSON_AddItemToObject(JsonObject1, "code", cJSON_CreateNumber(4001));
				cJSON_AddItemToObject(JsonObject1, "msg", cJSON_CreateString("token 过期，请重新登入!"));
				sendJson(JsonObject1);
				istmp = false;
			}
			SAFE_DELETE(ploginUserInfo);
			it = mMapSession.erase(it);
		}
		else {
			if (it->first == Authorization) {
				bIsExist = true;
}
			++it;
}
	}
	if (!bIsExist) {
		istmp = bIsExist;
	}
	LOGFMTI("mMapSession.size() : %d", mMapSession.size());
#endif
	return istmp;
}

int CHTTPSession::httpMessageGet() {
	CData ApiStr = getHeader();
	ApiStr.clean("?", true);

	if (startsWith(ApiStr.ToString(), "/api/")) {
		httpMessageGetApi(ApiStr);
	}
	else {
		httpMessageGetFile();
	}

	return 0;
}

int CHTTPSession::httpMessageGetFile()
{
	CData sFileName = get_object();
	CData ApiStr = getHeader();
	ApiStr.clean("?", true);
	sFileName.clean("?", true);

	std::lock_guard<std::mutex> lock(MutexMapFile);
	std::map<std::string, std::string>::iterator Iter;
	if (sFileName.empty()) { sFileName = "index.html";LOGFMTI("----------"); }
	LOGFMTI("%s", sFileName.c_str());
	if ((Iter = mMapFile.find(sFileName.ToString())) != mMapFile.end()) {
		sendFiles(Iter->second.c_str());
	}
	else {
		send404Message(sFileName.c_str(), sFileName.size());
		LOGFMTE("%s", sFileName.c_str());
	}

	return 0;
}

int CHTTPSession::httpMessageGetApi(CData & ApiStr)
{
	std::vector<std::string> paths = split(ApiStr.ToString(), "/");
	//WarnL << _path;
	if (paths.size() > 1)
	{
		const std::string model = paths.at(2);
		auto it = m_funModel.find(model);
		if (it != m_funModel.end()) {
			result res;
			it->second->update(paths, this);
		}
		else {
			// std::cout << "API not found or not supported for the request method. : " << ApiStr.c_str() << std::endl;
			return -1;
		}
	}


	// auto it = apiMapGet.find(ApiStr.ToString());
	// if (it != apiMapGet.end()) {
	// 	result res;
	// 	(this->*(it->second.callback))(&res);
	// }
	// else {
	// 	// std::cout << "API not found or not supported for the request method. : " << ApiStr.c_str() << std::endl;
	// 	return -1;
	// }
	return 0;
}

int CHTTPSession::httpMessageOPTIONS() {
	sendJsonMessage("", 0);
	return 0;
}

int CHTTPSession::httpMessagePost() {
	CData ApiStr = getHeader();
	ApiStr.clean("?", true);
	if (httpMessage1(ApiStr) == 0) {

	}
	else if (httpMessage4(ApiStr) == 0) {

	}
	else
	{
		std::string Authorization = GetAuthorization();
		if (CheckToken(Authorization))
		{
			httpMessage2(ApiStr);
		}
#if TOKEN
		else {
			cJSON* JsonObject1 = cJSON_CreateObject();
			cJSON_AddItemToObject(JsonObject1, "code", cJSON_CreateNumber(4001));
			cJSON_AddItemToObject(JsonObject1, "msg", cJSON_CreateString("token 过期，请重新登入!"));

			sendJson(JsonObject1);
		}
#endif
	}
	return 0;
}

int CHTTPSession::httpMessage() {
	return 0;
}

int CHTTPSession::httpMessage1(CData & ApiStr) {
	// auto it = apiMap1.find(ApiStr.ToString());
	// if (it != apiMap1.end()) {
	// 	result res;
	// 	(this->*(it->second.callback))(&res);
	// }
	// else {
	// 	// std::cout << "API not found or not supported for the request method. : " << ApiStr.c_str() << std::endl;
	// 	return -1;
	// }

	return 0;
}

int CHTTPSession::httpMessage2(CData & ApiStr) {
	// auto it = apiMap2.find(ApiStr.ToString());
	// if (it != apiMap2.end()) {
	// 	// (it->second.first)(*this); // Call the mapped member function with the current instance.
	// 	result res;
	// 	res.payload = GetContent().ToString();
	// 	(this->*(it->second.callback))(&res);
	// }
	// else if (0 == httpMessage3(ApiStr)) {
	// 	std::cout << "httpMessage3" << std::endl;
	// }
	// else {
	// 	CData Response;
	// 	CHttpResponse::make_404_error(Response);
	// 	sendMessage(Response.c_str(), Response.size());
	// 	std::cout << "API not found or not supported for the request method : " << ApiStr.ToString() << std::endl;
	// 	return -1;
	// }

	return 0;
}

int CHTTPSession::httpMessage3(CData & ApiStr) {
	return 0;
}

int CHTTPSession::httpMessage4(CData & ApiStr) {
	// auto it = apiMap4.find(ApiStr.ToString());
	// if (it != apiMap4.end()) {
	// 	result res;
	// 	(this->*(it->second.callback))(&res);
	// 	// saveLog(&(it->second), &res);
	// }
	// else {
	// 	// std::cout << "API not found or not supported for the request method. : " << ApiStr.c_str() << std::endl;
	// 	return -1;
	// }

	return 0;
}

void CHTTPSession::OnReceive(const char* data, int len)
{
	// LOGFMTI("%s",data);
	// LOGFMTE("========================");
	// LOGFMTE("========================");
	// LOGFMTE("=======================");
	char* mchar = (char*)data;
	int lengh = len;
	LOGFMTI("len1:%d", len);
	int count = NUM_MAX;
	while (count--) {
		LOGFMTI("count1:%d", count);
		int nRet = parse(mchar, lengh);
		LOGFMTI("ContentLength:%d", GetContentLength());
		if (nRet > 0) {
			// string::size_type idx;
			CData sFileName = get_object();
			CData ApiStr = getHeader();
			ApiStr.clean("?", true);
			sFileName.clean("?", true);
			if (HTTP_METHOD_GET == GetMethod()) {
#if defined AQRH_WEBSERVER
#if AQRH_WEBSERVER_DEBUG
				httpMessageGet();
#else
				send404Message("", 0);//走 nginx
#endif

#else
				httpMessageGet();
#endif
			}
			else if (HTTP_METHOD_OPTIONS == GetMethod()) {
				httpMessageOPTIONS();
			}
			else if (HTTP_METHOD_POST == GetMethod()) {
				httpMessagePost();
			}
			else {
				send404Message("", 0);
				LOGFMTE("HttpMethodType : %s\n", GetMethod());
			}

			mchar += nRet;
			lengh -= nRet;
			if (lengh == 0) {
				break;
			}
	}
		else if (0 == nRet) {
			break;
		}
		else if (-1 == nRet) {
			lengh = 0;
			break;
		}
}
	if (count <= 0) {
		LOGFMTI("count:%d", count);
	}
}

int CHTTPSession::sendFiles(const char* filePath)
{
	int errNum = 0;
	FILE* fp = fopen(filePath, "rb");

	if (NULL != fp) {
		int timeCur = TimGetTicks();
		size_t file_size = GetFileSize(filePath);
		CHttpBuffer HttpBuffer(4096);
		size_t len = CHttpResponse::make(HttpBuffer.m_chars, fp, filePath, file_size);
		sendBodyMessage(HttpBuffer.m_chars, len);
		CHttpBuffer HttpBuffer_body;
		char* ptr = HttpBuffer_body.m_chars;
		size_t bytesRead = 0;
		while ((bytesRead = fread(ptr, 1, HTTPUTIL_BUFFER_SIZE - 1, fp)) > 0) {
			sendBodyMessage(HttpBuffer_body.m_chars, bytesRead);
		}
		fclose(fp);
		int timeLast = TimGetTicks();
		return 0;
	}
	else
	{
		errNum = errno;
		LOGFMTE("open %s fail errno = % d reason = % s", filePath, errNum, strerror(errNum));
	}

	return -1;
}

void CHTTPSession::sendJson(cJSON * json) {
	char* ptr = cJSON_Print(json);
	sendSessionMessage(ptr);
	cJSON_Delete(json);
	SAFE_FREE(ptr);
}

void CHTTPSession::sendSessionMessage(const char* data)
{
	if (!data) { LOGFMTE("data null");return; }
	sendJsonMessage(data, strlen(data));
}

void CHTTPSession::device_list(result * res) {
	//cJSON* JsonObject1 = cJSON_CreateObject();

	//cJSON_AddItemToObject(JsonObject1, "code", cJSON_CreateNumber(200));
	//cJSON_AddItemToObject(JsonObject1, "msg", cJSON_CreateString("成功"));
	//cJSON_AddItemToObject(JsonObject1, "data", cJSON_CreateString(""));

	cJSON* device = cJSON_CreateObject();
	cJSON_AddStringToObject(device, "ID", "34020000002000000220");
	cJSON_AddStringToObject(device, "Name", "hhahahahahhaahah平台");
	cJSON_AddStringToObject(device, "CustomName", "");
	cJSON_AddStringToObject(device, "Manufacturer", "LiveGBS v240322");
	cJSON_AddStringToObject(device, "Type", "GB");
	cJSON_AddStringToObject(device, "Password", "");
	cJSON_AddStringToObject(device, "MediaTransport", "TCP");
	cJSON_AddStringToObject(device, "MediaTransportMode", "passive");
	cJSON_AddStringToObject(device, "StreamMode", "");
	cJSON_AddStringToObject(device, "CommandTransport", "UDP");
	cJSON_AddStringToObject(device, "RemoteIP", "192.168.0.23");
	cJSON_AddNumberToObject(device, "RemotePort", 15060);
	cJSON_AddBoolToObject(device, "Online", 1);
	cJSON_AddBoolToObject(device, "RecordCenter", 0);
	cJSON_AddBoolToObject(device, "RecordIndistinct", 0);
	cJSON_AddBoolToObject(device, "CivilCodeFirst", 0);
	cJSON_AddBoolToObject(device, "KeepOriginalTree", 1);
	cJSON_AddBoolToObject(device, "ChannelOverLoad", 0);
	cJSON_AddNumberToObject(device, "ChannelCount", 40);
	cJSON_AddStringToObject(device, "RecvStreamIP", "");
	cJSON_AddStringToObject(device, "SMSID", "");
	cJSON_AddStringToObject(device, "SMSGroupID", "");
	cJSON_AddStringToObject(device, "ContactIP", "");
	cJSON_AddStringToObject(device, "Charset", "GB2312");
	cJSON_AddNumberToObject(device, "CatalogInterval", 3600);
	cJSON_AddNumberToObject(device, "SubscribeInterval", 0);
	cJSON_AddBoolToObject(device, "CatalogSubscribe", 0);
	cJSON_AddBoolToObject(device, "AlarmSubscribe", 0);
	cJSON_AddBoolToObject(device, "PositionSubscribe", 0);
	cJSON_AddNumberToObject(device, "Longitude", 0);
	cJSON_AddNumberToObject(device, "Latitude", 0);
	cJSON_AddStringToObject(device, "DropChannelType", "");
	cJSON_AddStringToObject(device, "LastRegisterAt", "2024-04-18 18:15:16");
	cJSON_AddStringToObject(device, "LastKeepaliveAt", "2024-04-18 18:18:11");
	cJSON_AddStringToObject(device, "CreatedAt", "2024-03-25 16:48:14");
	cJSON_AddStringToObject(device, "UpdatedAt", "2024-04-18 18:18:11");

	// 创建 DeviceList 数组
	cJSON* deviceList = cJSON_CreateArray();
	cJSON_AddItemToArray(deviceList, device);

	// 创建主对象
	cJSON* root = cJSON_CreateObject();
	cJSON_AddNumberToObject(root, "DeviceCount", 1);
	cJSON_AddItemToObject(root, "DeviceList", deviceList);

	sendJson(root);
}

void CHTTPSession::device_channellist(result * res) {
	// 创建 ChannelList 数组
	cJSON* channelList = cJSON_CreateArray();

	// 创建第一个通道对象
	cJSON* channel1 = cJSON_CreateObject();
	cJSON_AddStringToObject(channel1, "Address", "");
	cJSON_AddNumberToObject(channel1, "Altitude", 0);
	cJSON_AddBoolToObject(channel1, "AudioEnable", false);
	cJSON_AddNumberToObject(channel1, "BatteryLevel", 0);
	cJSON_AddStringToObject(channel1, "Block", "");
	cJSON_AddNumberToObject(channel1, "Channel", 1);
	cJSON_AddStringToObject(channel1, "CivilCode", "3402");
	cJSON_AddBoolToObject(channel1, "CloudRecord", false);
	cJSON_AddStringToObject(channel1, "CreatedAt", "2024-04-14 09:59:45");
	cJSON_AddBoolToObject(channel1, "Custom", false);
	// 添加其他属性...
	cJSON_AddStringToObject(channel1, "UpdatedAt", "2024-04-18 18:19:35");

	// 将第一个通道对象添加到 ChannelList 数组
	cJSON_AddItemToArray(channelList, channel1);

	// 创建第二个通道对象，以此类推...
	cJSON* channel2 = cJSON_CreateObject();
	cJSON_AddStringToObject(channel2, "Address", "");
	cJSON_AddNumberToObject(channel2, "Altitude", 0);
	cJSON_AddBoolToObject(channel2, "AudioEnable", false);
	cJSON_AddNumberToObject(channel2, "BatteryLevel", 0);
	cJSON_AddStringToObject(channel2, "Block", "");
	cJSON_AddNumberToObject(channel2, "Channel", 2);
	cJSON_AddStringToObject(channel2, "CivilCode", "3402");
	cJSON_AddBoolToObject(channel2, "CloudRecord", false);
	cJSON_AddStringToObject(channel2, "CreatedAt", "2024-04-17 18:01:07");
	cJSON_AddBoolToObject(channel2, "Custom", false);
	// 添加其他属性...
	cJSON_AddStringToObject(channel2, "UpdatedAt", "2024-04-18 18:19:35");

	cJSON_AddItemToArray(channelList, channel2);

	// 创建主对象
	cJSON* root = cJSON_CreateObject();
	cJSON_AddNumberToObject(root, "ChannelCount", 40);
	cJSON_AddItemToObject(root, "ChannelList", channelList);

	sendJson(root);
}